<template>
    <div class="teamuserdata">
        <div class="row dfl" :style="{
            textAlign: 'center'
        }">
            <el-tooltip class="box-item" effect="dark" content="提交的题目评测结果为全部Accepted(满分)的题目数量" placement="bottom">
                <div title class="col">全AC提交次数：{{ ACrank }}</div>
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" placement="bottom">
                <template #content>
                    提交的评测题目中，AC的测试点占总评测点的数量。
                    <br />该数据会针对题目去重，只考虑题目得分最佳情况。如：
                    <br />某道题提交了3次评测，第一次1个测试点AC、第二次2个、第三次3个。
                    <br />取AC数最高的第3次计入3，其他两次数据忽略。
                </template>
                <div class="col">AC测试点数：{{ data2[0]?.count || 0 }}</div>
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" placement="bottom">
                <template #content>
                    提交的评测题目中，测试点是AC的比例。
                    <br />该数据会针对题目去重，只考虑题目得分最佳情况。如：
                    <br />某道题提交了3次评测，第一次1个测试点AC、第二次2个、第三次3个。
                    <br />取AC数最高的第3次计入3，其他两次数据忽略。
                </template>
                <div class="col" :style="{
                    textAlign: 'center'
                }">
                    测试点得分率：
                    <span>{{ dfl || 0 }}</span>%
                </div>
            </el-tooltip>
            <div class="col" :style="{ 'text-align': 'center' }">
                <div style="text-align: left; width: 200px;display: inline-block;">
                    <el-select-v2 size="default" v-model="usersd" :options="options" filterable></el-select-v2>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col char-1 char">
                <header>测试点评测概况</header>
                <chartVue :color="data2.length ? data2.map(e => e.color) : color" :data="data2" :height="270"></chartVue>
            </div>
            <div class="col char-2 char">
                <header>全AC题目标签</header>
                <chartVue :color="data3.length ? data3.map(e => e.color) : color" :data="data3" :height="270"></chartVue>
            </div>
            <div class="col char-1 char">
                <header>全评测题目标签</header>

                <chartVue :color="data4.length ? data4.map(e => e.color) : color" :data="data4" :height="270"></chartVue>
            </div>
        </div>
        <div class="row" :style="{ marginTop: '24px' }">
            <div class="col-6  char-3" title="该数据统计团队创建后，所有团队成员的观看视频数，【不包括】团队创建前的视频观看">
                <div class="char">
                    <header>团队观看视频数</header>
                    <chart2Vue :data="data6" :height="270"></chart2Vue>
                </div>

            </div>
            <div class="col-6  char-4" title="该数据统计团队所有成员的历史提交测评数，【包括】团队创建前的评测提交">
                <div class="char">
                    <header>成员提交评测数</header>
                    <chart2Vue :data="data5" :height="270"></chart2Vue>
                </div>

            </div>
        </div>
        <div class="row" :style="{ marginTop: '24px' }" title="该数据统计团队所有成员的历史提交评测时间分布，【包括】团队创建前的评测提交">
            <div class="col char char-5">
                <header>成员做题时间分布</header>
                <chart2Vue :data="data7" :height="270"></chart2Vue>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { asyncselectchart, asyncselectteamselectuser, asyncselectuser, asyncteamuserquestion } from '../../../api'
import Studycodemodel from '../../../mysql_interface/studycodemodel'
import chartVue from '../../../components/antv/chart.vue'
import chart2Vue from '../../../components/antv/chart2.vue'
import { useStore } from 'vuex'
import { Storekey } from '../../../interface'
import { assign, debounce } from 'underscore'
import FetchApi, { logdata } from '../../../logs/api'
import moment from 'moment'
import { useRoute, useRouter } from 'vue-router'
const prop = defineProps<{ formdata: { teamid?: number, userid?: number, formdate: Date, todate: Date }, teamusers: Studycodemodel.Iteamuser[], data: Studycodemodel.Iteam }>()
const svg = ['#icon-rank_1', '#icon-rank_2', '#icon-rank_3']

const dfl = ref(0)

const usersd = ref(Number(prop.formdata.userid) || 0)

const ACrank = ref(0)

const options = computed<{ label?: string, value?: number }[]>(() => {
    return [{ value: 0, label: '全部成员' }].concat(...prop.teamusers.map(e => { return { value: e.user?.ID, label: e.user?.name } }))
})

onMounted(() => {
    debounce1()
})

const router = useRouter()

const data1 = ref<{ ID?: number, name?: string, ACcount?: number, df?: number, headportrait?: string }[]>([])
const data2 = ref<{ name: string, count: number, color: string }[]>([])

const loading = ref(false)
watch(() => prop.formdata, () => {
    debounce1()
})

watch(() => usersd.value, (usersd) => {
    router.push({
        query: {
            usersd
        }
    })
})

const color = ['#B83914', '#CF4017', '#EC4313', '#EB6C47', '#EE8263', '#FF8461', '#FF9C80', '#FFB099', '#FFC3B2', '#FFD7CC', '#FFEBE5']
const data3 = ref<{ name: string, count: number, color: string }[]>([])
const data4 = ref<{ name: string, count: number, color: string }[]>([])
const data5 = ref<{ name: string, count: number }[]>([])
const data6 = ref<{ name: string, count: number }[]>([])
const data7 = ref<{ name: string, count: number }[]>([])

const store = useStore(Storekey)

const label = computed(() => {
    return store.state.label?.rows || []
})

const debounce1 = debounce(start, 100)


async function start() {
    const formdata = assign({}, prop.formdata, {
        userid: usersd.value ? usersd.value : null,

    })
    if (prop.formdata.teamid) {
        loading.value = true
        const t = await asyncteamuserquestion(formdata)
        data3.value = t.AClabel.sort((a, b) => b.count - a.count).map<{ name: string; count: number, color: string }>((e, k) => {
            return {
                name: label.value.find(t => t.ID === e.labelid)?.name as string,
                count: e.count,
                color: color[k] ? color[k] : '#D9D9D9'
            }
        })
        data4.value = t.Alllabel.sort((a, b) => b.count - a.count).map<{ name: string; count: number, color: string }>((e, k) => {
            return {
                name: label.value.find(t => t.ID === e.labelid)?.name as string,
                count: e.count,
                color: color[k] ? color[k] : '#D9D9D9'

            }
        })
        let timetype: 'w' | 'm' = 'w'
        let _tmp = 0
        let _all = 0

        ACrank.value = t.ACrank + t.ACmatch

        const _tmparr: Array<Studycodemodel.Iuserquestion | Studycodemodel.Imatchuserquestion> = []
        t.userquestion.forEach(f => {
            const count = f.resultdataarr?.filter(e => e === 'AC').length || 0
            const _e = _tmparr.findIndex(n => n.questionid === f.questionid)
            if (_e === -1) {
                _tmparr.push(f)
            } else {
                const _count = _tmparr[_e].resultdataarr?.filter(e => e === 'AC').length
                if (_count ? _count : 0 < count) {
                    _tmparr[_e] = f
                }
            }
            _all = _all + Number(f.resultdataarr?.length || 0)
            _tmp = _tmp + Number(f.resultdataarr?.filter(e => e === 'AC').length || 0)
        })
        t.matchquestion.forEach(f => {
            const count = f.resultdataarr?.filter(e => e === 'AC').length || 0
            const _e = _tmparr.findIndex(n => n.questionid === f.questionid)
            if (_e === -1) {
                _tmparr.push(f)
            } else {
                const _count = _tmparr[_e].resultdataarr?.filter(e => e === 'AC').length
                if (_count ? _count : 0 < count) {
                    _tmparr[_e] = f
                }
            }
            _all = _all + Number(f.resultdataarr?.length || 0)
            _tmp = _tmp + Number(f.resultdataarr?.filter(e => e === 'AC').length || 0)
        })
        // ac 占比
        data2.value = t.allrank ? [{ name: 'AC测试点', count: _tmp, color: '#FF8461' }, { name: '非AC测试点', count: _all - _tmp, color: '#FFE7DB' }] : []

        // 得分占比
        dfl.value = Math.floor(_tmp / _all * 100)
        const num = new Date(prop.formdata.todate).getTime() - new Date(prop.formdata.formdate).getTime()
        const n = num / 1000 / 60 / 60 / 24 / 7
        timetype = 'm'

        // if (n > 14) {
        //     timetype = 'm'
        // } else {
        //     timetype = 'w'
        // }

        data7.value = Array.from({ length: 24 }).map((v, k) => {
            const z = t.groupkuserquestion.find(f => f.hover == k)
            if (z) {
                return {
                    name: k + '点',
                    count: z.count
                }
            }
            return {
                name: k + '点',
                count: 0
            }
        })

        asyncselectchart({
            teamid: prop.formdata.teamid,
            starttime: prop.formdata.formdate,
            endtime: prop.formdata.todate,
            timetype: timetype === 'w' ? '%Y-%v周' : '%Y-%m月',
            userids: usersd.value ? [usersd.value] : undefined
        }).then(f => {
            data5.value = f.userquestion.map(e => {
                return {
                    name: e.day,
                    count: e.count
                }
            })
        })


        watchvideo(timetype).then(({ data }) => {
            data6.value = data.map((e: { count: number, day: string }) => {
                return {
                    name: `${e.day}${timetype === 'm' ? '月' : '周'}`,
                    count: Number(e.count)
                }
            })
        }).catch(console.log)


        loading.value = false

    }

    async function watchvideo(timetype: string) {
        const formInline: logdata = {
            query: "* | with_pack_meta",
            line: 99,
            offset: 0,
            projectName: "htetest1",
            logstoreName: "ojhte",
            from: prop.formdata.formdate,
            to: prop.formdata.todate,
            reverse: true,
        };
        let str = ''
        if (usersd.value) {
            if (usersd.value === prop.data.userid) {
                str = `and _phonenum_:${prop.data.user?.phonenum}`
            } else {
                const [user] = await asyncselectteamselectuser({ teamid: prop.data?.ID, userid: usersd.value, phonenum: true, gid: true })
                if (user.user?.phonenum) {
                    str = `and _phonenum_:${user.user?.phonenum}`
                } else {
                    str = `and _cid_:${user.user?.gid}`
                }
            }

        }
        // const query = `* and type:video and _teamids_:${prop.data.ID} ${str} | select  ${timetype === 'm' ? 'month' : 'week'}(from_unixtime(__time__)) as day, count(__time__) as count group by day order by day`;
        const query = `* and type:video and _teamids_:${prop.data.ID} ${str} | select  date_format(date_trunc( '${timetype === 'm' ? 'month' : 'week'}',__time__), '${timetype === 'm' ? '%Y-%m' : '%Y-%v'}') as day, count(__time__) as count group by day order by day`;
        return FetchApi(
            Object.assign({}, formInline, {
                query,
            })
        );
    }
}
</script>

<style scoped>
.dfl {
    height: 54px;
    border-radius: 8px;
    line-height: 54px;
    background-image: url(https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/oj_1_1/oj_tuanduishuju_ceshidianbanfenbi.png);
    background-repeat: no-repeat;
    background-size: cover;
    font-size: 18px;
    color: #fff;
    margin-top: 24px;
    margin-bottom: 24px;
}

.char-1 {
    width: 350px;
}

.char-2 {
    margin-right: 24px;
    margin-left: 24px;
    width: 350px;
}

.char-3 {
    padding-right: 6px;
    padding-left: 0px;
}

.char-4 {
    padding-left: 6px;
    padding-right: 0px;

}

.char {
    height: 360px;
    padding-top: 24px;
    font-size: 18px;
    color: var(--color-43);
    text-align: center;
    background-color: var(--color-f5);
    box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1),
        0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
}

.teamuserdata {
    padding: 12px;
}

header {
    font-size: 16px;
    margin-bottom: 12px;
}
</style>
